from django.shortcuts import render_to_response, redirect
from django.contrib.auth import logout, login, authenticate
from django.core.context_processors import csrf
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from os.path import splitext
#from gtp.c.tabconvert import system as t_system

from gtp.archive.models import *

def csrf_resp(req, temp, c={}):
    c.update(csrf(req))
    return render_to_response(temp, c)


def v_index(request):
    if request.user.is_authenticated():
        return render_to_response("home.html", { 'username': request.user.username, 'tracks': request.user.track_set.all()})
    else:
        return render_to_response("index.html", { "tracks": Track.objects.all()[:10]} )


def v_register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'])
            login(request, user)
            return redirect("/")
    else:
        form = UserCreationForm()
    
    return csrf_resp(request, "registration/register.html", { 'form' : form })

@login_required
def v_upload(req):
    if req.method == 'POST':
        form = TrackForm(req.POST, req.FILES, instance=Track(user=req.user))
        if form.is_valid():
            form.save()
            return redirect("/")
    else:
        form = TrackForm()

    return csrf_resp(req, "upload.html", { 'form' : form, 'username': req.user.username })

def v_track(req):
    pk = req.GET['id']
    track = Track.objects.get(id=pk)
    own = req.user == track.user
    return render_to_response("track.html", { "username": req.user.username, "track": track, "own": own })

@login_required
def v_track_delete(req):
    pk = req.GET['id']
    track = Track.objects.get(id=pk)
    if 'force' in req.GET:
        if req.user == track.user:
            track.delete()
            return redirect("/")
    return render_to_response("track_delete.html", { "username": req.user.username, "track":track })


def v_search(req):
    q = req.GET["q"].split()
    tracks = Track.objects.all()
    for w in q:
        tracks = tracks.filter(title__icontains=w)
    tracks = tracks.distinct()
    return render_to_response("search.html", { "username": req.user.username, "tracks": tracks })


def v_track_download(req):
    pk = req.GET['id']
    track = Track.objects.get(id=pk)
    resp = HttpResponse(track.data.read(), content_type="application/gtp")
    name, ext = splitext(track.data.name)
    resp['Content-Disposition'] = 'attachment; filename="' + track.artist + ' - ' + track.title + ext + '"'
    return resp
